//
//  ATShareTool.m
//  AT
//
//  Created by xiao6 on 15/7/22.
//  Copyright (c) 2015年 Summer. All rights reserved.
//

#import "ATShareTool.h"
#import <WXApi.h>

@interface ATShareTool () <WXApiDelegate>
@property (nonatomic, copy) void(^completion)(ATShareResponse status, id response);
@end
@implementation ATShareTool
static ATShareTool *_instance;
+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+ (void)shareInit {
    [WXApi registerApp:@"wx60f88f2f95b579a6"];
}

+ (BOOL)isWXAppInstalled {
    return [WXApi isWXAppInstalled];
}

+ (void)sendWechatLogin:(void (^)(ATShareResponse, NSString *))completion {
    [ATShareTool shareInstance].completion = completion;
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = [UIApplication sharedApplication].appBundleID;
    [WXApi sendAuthReq:req viewController:[UIApplication sharedApplication].keyWindow.rootViewController delegate:[ATShareTool shareInstance]];
}

+ (BOOL)handleOpenURL:(NSURL *)url {
    return [WXApi handleOpenURL:url delegate:[ATShareTool shareInstance]];;
}

- (void)onResp:(BaseResp*)resp {
    ATShareResponse status = ATShareResponseFailture;
    id response = resp;
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        response = ((SendAuthResp *)resp).code;
        if (resp.errCode == 0) {
            status = ATShareResponseSuccess;
        }
    }
    if (self.completion) {
        self.completion(status, response);
        self.completion = nil;
    }
}
@end
